<template>
  <div>
    <div class="container">
      <div class="left">
        <div>
          <el-button type="primary" :icon="Plus" @click="addOrgFn"
            >新增</el-button
          >
          <el-button type="primary" :icon="Edit" @click="editOrgFn"
            >编辑</el-button
          >
          <el-button type="default" :icon="Delete" @click="del">删除</el-button>
        </div>

        <el-tree
          :data="treeData"
          show-checkbox
          :props="defaultProps"
          @node-click="handleNodeClick"
          :current-node-key="selectKeys"
          :highlight-current="true"
          :check-on-click-node="true"
          @getCurrentKey="getCurrentKey"
          node-key="id"
          @getCurrentNode="getCurrentNode"
        />
      </div>
      <div class="right">
        <el-table
          :height="tableHeight"
          :data="rightList"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
        >
          <el-table-column width="100" align="center" label="序号" fixed>
            <template v-slot="scope">
              {{ indexMethod(scope.$index, query.pageIndex, query.pageSize) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="parentName"
            label="上级区域名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="code"
            label="区域编码"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="区域名称"
            align="center"
          ></el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="getTitle(visibleType)" v-model="editVisible" width="30%">
      <el-form label-width="120px" ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="parentName" label="上级区域名称">
          <el-input v-model="form.parentName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item prop="name" label="区域名称">
          <el-input v-model="form.name" placeholder="请输入区域名称"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="区域编码">
          <el-input v-model="form.code" placeholder="请输入区域编码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer v-if="visibleType !== 'watch'">
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm(formRef)"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { View, Search, Delete, Edit, Plus } from "@element-plus/icons-vue";
import {
  orgList,
  getDevice,
  addOrg,
  deleteDevice,
  editDevice,
  delOrg,
  editOrg,
} from "../../../api/index";
import { indexMethod, getViewPortHeight } from "../../../utils/tools";
import type Node from "element-plus/es/components/tree/src/model/node";
import type { FormInstance, FormRules } from "element-plus";

const tableHeight = getViewPortHeight() - 220;

interface TableItem {
  id: number;
  name: string;
  parentName: string;
  code: string;
  parentId: string;
}

interface Tree {
  name: string;
}

const selectOrg: any = ref("");
const rightList: any = ref([]);
const handleNodeClick = (data: any, checked: any, indeterminate: any) => {
  if (checked.checked) {
    selectOrg.value = data;
    if (data.children && data.children.length) {
      rightList.value = data.children;
    } else {
      rightList.value = [];
    }
  } else {
    selectOrg.value = "";
    rightList.value = [];
  }
};

const getCurrentKey = (value: any) => {
  console.log("value", value);
};

const getCurrentNode = (value: any) => {
  console.log("value", value);
};

const addOrgFn = () => {
  if (!selectOrg.value) {
    ElMessage.error("请选择节点！");
  } else {
    visibleType.value = "add";
    editVisible.value = true;
    form.name = "";
    form.parentName = selectOrg.value.name;
    form.parentId = selectOrg.value.id;
    form.code = "";
  }
};

const editOrgFn = () => {
  if (!selectOrg.value) {
    ElMessage.error("请选择节点！");
  } else {
    visibleType.value = "edit";
    editVisible.value = true;
    form.name = selectOrg.value.name;
    form.parentName = selectOrg.value.parentName;
    form.parentId = selectOrg.value.parentId;
    form.code = selectOrg.value.code;
    form.id = selectOrg.value.id;
  }
};

const del = () => {
  if (!selectOrg.value) {
    ElMessage.error("请选择节点！");
  } else {
    if (selectOrg.value.children && selectOrg.value.children.length) {
      ElMessage.error("该节点拥有子节点，不允许删除！");
    } else {
      ElMessageBox.confirm("确定要删除该节点吗？", "提示", {
        type: "warning",
      })
        .then(async () => {
          delOrg([selectOrg.value.id]).then((res: any) => {
            if (res.code === 200) {
              ElMessage.success("删除成功！");
              getData();
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  }
};

const defaultProps = {
  children: "children",
  label: "label",
};

const treeData = ref([]);
const selectKeys = ref([]);
const getData = () => {
  orgList().then(async (res: any) => {
    const dd: any = await delTreeData(res);
    treeData.value = await delTreeData(res);
  });
};

const delTreeData = (treeData: any) => {
  const list: any = [];
  treeData.forEach((item: any) => {
    if (item.children && item.children.length) {
      const temp = delTreeData(item.children);
      if (temp.length) {
        list.push({
          ...item,
          label: item.name,
          children: temp,
        });
      }
    } else {
      list.push({
        ...item,
        label: item.name,
      });
    }
  });
  return list;
};

const getTitle = (key: string) => {
  switch (key) {
    case "edit":
      return "编辑节点";
    case "add":
      return "新增节点";
    default:
      return null;
  }
};
const query = reactive({
  address: "",
  testNo: "",
  pageIndex: 1,
  pageSize: 10,
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);

getData();

// 删除操作
const handleDelete = (row: any) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      const res: any = await deleteDevice({ id: row.id });
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getData();
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 表格编辑时弹窗和保存
const editVisible = ref(false);
const formRef = ref<FormInstance>();
let form = reactive({
  name: "",
  parentName: "",
  code: "",
  id: "",
  parentId: "",
});
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入区域名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入区域代码", trigger: "blur" }],
});
const visibleType = ref("add");
const handleEdit = async (type: string, row: any) => {
  visibleType.value = type;
  editVisible.value = true;
  const res: any = await getDevice({ id: row.id });
  if (res.code === 200) {
    form.name = res.rows.name || "";
    form.parentName = res.rows.parentName || "";
    form.code = res.rows.code || "";
  } else {
    ElMessage.error("获取详情信息失败！");
  }
};

// 新增
const add = () => {
  visibleType.value = "add";
  editVisible.value = true;
  form.name = "";
  form.parentName = "";
  form.code = "";
};

// 保存新增
const save = async () => {
  let res: any = null;
  if (visibleType.value === "edit") {
    res = await editOrg({
      name: form.name,
      parentName: form.parentName,
      parentId: form.parentId,
      code: form.code,
      orgId: form.id,
    });
  } else {
    res = await addOrg({
      name: form.name,
      parentName: form.parentName,
      code: form.code,
      parentId: form.parentId,
    });
  }

  if (res.code === 200) {
    editVisible.value = false;
    ElMessage.success("保存成功！");
    getData();
  } else {
    ElMessage.error("保存失败！");
  }
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (valid) {
      save();
    } else {
      return false;
    }
  });
};
</script>
<style scoped lang="less">
@import "./index.less";
</style>
